<script setup>
defineOptions({ name: 'UserAvator' })
import CardPage from '@/components/CardPage.vue'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import 'element-plus/dist/index.css'
import { userProfileService, userUpdateAvatorService } from '@/api/user'
const loaderRef = ref(null)
// 获取图片
const avatar = ref('')
const getAvatar = async () => {
  const res = await userProfileService()
  avatar.value = res.data.user_pic
}
getAvatar()
// 选择图像出现文件选择器
const openFileChooser = () => {
  // el-upload 组件实例的根 DOM 在 $el，下述方式在绝大多数 ElementPlus 版本有效
  const input = loaderRef.value?.$el?.querySelector('input[type="file"]')
  if (input) {
    input.click()
  } else {
    // 兜底：如果没找到可以提示或 fallback 到创建 input
    ElMessage.warning('无法打开文件选择器')
  }
}
// 处理上传的文件转为base64字符串
const disabled = ref(true)
const selectAvatar = async (file) => {
  console.log(file)
  avatar.value = await fileToBase64(file.raw)
  disabled.value = false
}
// 将file对象转为base64字符串
function fileToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => {
      resolve(reader.result)
    }
    reader.onerror = (error) => {
      reject(error)
    }
    reader.readAsDataURL(file)
  })
}

// 提交头像
const submitAvatar = async () => {
  const res = await userUpdateAvatorService(avatar.value)
  ElMessage.success(res.message)
}
</script>
<template>
  <card-page title="更换头像">
    <el-upload
      class="avatar-uploader"
      :on-change="selectAvatar"
      ref="loaderRef"
      :auto-upload="false"
      :show-file-list="false"
    >
      <img v-if="avatar" :src="avatar" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><i-ep-plus /></el-icon>
    </el-upload>
    <el-button
      type="primary"
      size="large"
      style="margin-top: 20px"
      @click="openFileChooser"
      >选择图像</el-button
    >
    <el-button
      type="success"
      size="large"
      style="margin-top: 20px; margin-left: 10px"
      @click="submitAvatar"
      :disabled="disabled"
      >上传图像</el-button
    >
  </card-page>
</template>
<style lang="scss" scoped>
.avatar-uploader {
  .avatar {
    display: block;
  }
  :deep(.el-upload) {
    width: 600px;
    height: 600px;
    border: 1px dashed #8c939d;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    i {
      height: 2rem;
      width: 2rem;
      svg {
        width: 2rem;
        height: 2rem;
      }
    }
    img {
      height: 600px;
      width: 600px;
      object-fit: cover; /* 图片居中裁剪，填满容器（不拉伸） */
    }
  }
  :deep(.el-upload:hover) {
    border-color: var(--el-color-primary);
  }
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
}
</style>
